<?php
import('ORG.Util.Function');
import('ORG.Util.QPage');
import('@.Org.PowerTool');

class PowerAction extends CommonAction {	
	
	/* 初始化  */
	public function _initialize(){
		parent::_initialize();
		$param         =     $this->_get('_URL_');
		$controller    =     $param[0];
		$action        =     $param[1];	
		//language
		$lang          =     L($action);//获取语言包	
		
		$this->assign('current',$lang);
		$this->assign('lang',$lang);
		$this->assign('manage','管理');
	}
	
	/**
	 * 后台管理人员列表
	 * 
	 */
	public function adminuser_list(){		
	    $this->assign('adminUserList',  get_admin_userlist());	
		$this->display();
	}
	
	/**
	 * 添加后台管理人员
	 * 
	 */
	public function add_adminuser(){
		
		$Role              =    new Model('Role');
		$roleList          =    $Role->field('id,name')->select();
		
		$this->assign('roleList',$roleList);
		$this->display();
	}
	
	/**
	 * 处理添加后台管理人员
	 * Enter description here ...
	 * 
	 */
	public function add_adminuser_ok(){
		//建立一个空模型
		$Model					 =    new Model();
		//开启事物
		$Model->startTrans();
		
		$AdminUser               =    new Model('AdminUser');
		$RoleUser                =    new Model('RoleAdminuser');
		//获取数据
		$user_name               =    $this->_post('name');
		$password                =    md5($this->_post('password'));
		$email                   =    $this->_post('mail');
		$confirmpwd              =    md5($this->_post('confirmpwd'));
		$role_id                 =    $this->_post('role_id');
		//判断用户名是否重复
		$con                     =    "user_name='" . $user_name . "'";
		$result                  =    $AdminUser->where($con)->find();
				
		if($result) {
			$this->error('该用户名已经存在!');
			return;
		}	
		
		//判断密码是否相同
		if($confirmpwd != $password){
			$this->error('密码不相同!');
			return;
		}
		//判断用户组id是否为空
		if($role_id == ''){
			$this->error('用户组不能为空');
			return;
		}
		//添加用户
		$datas                     	=   array();
		$datas['user_name']        	=   $user_name;
		$datas['password']         	=   $password;
		$datas['email']            	=   $email;
		$datas['add_time']         	=   time();
		
		$id                        	=   $AdminUser->add($datas);	

		$list 						= 	array();
		$list['role_id']       		=   $role_id;
		$list['user_id']       		=   $id;		
		//分配权限			
		$result                		=   $RoleUser->add($list);
		$url                   		=   U('Power/adminuser_list');
		
		if($result && $id){
			$Model->commit();
			$this->success('添加管理员成功',$url);
		}else{
			$Model->rollback();
			$this->error('添加管理员失败',$url);
		}
	}	
	
	/**
	 * @管理员日志
	 */
	public function adminlog(){
		$this->display();	
	}
	
	/**
	 * @用户组列表:role_page
	 */
	public function role_list(){
		$Role          =    new Model('Role');
		$roleList      =    $Role->select();
		
		$this->assign('roleList',$roleList);
		$this->display();
	}	
	
	/**
	 * @添加用户组:add_role_page
	 * 
	 * 
	 */
	public function add_role(){
		$Node             =    new NodeModel('Node');
		//$controllerList   =    $Node->field('name,title')->where("level=2")->select();
		//$controllerList   =    $Node->field('id,pid,name,title,level')->select();
		$sql			=	"
							SELECT a2.*,a1.p_name
							FROM  `ybr_node` a2
							LEFT JOIN (							
							SELECT id, name p_name
							FROM ybr_node
							)a1 ON a1.id = a2.pid
							";
		$controllerList	=	$Node->query($sql);
		
		//递归排序
		$datas	=	$this->catsort1($controllerList,0,0);
		
		$list       =     array();		
		foreach ($datas as $v){
			$v['blank']    =    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev'] * 2);
			$list[]        =    $v;
		}
		$this->assign('controllerList',$list);
		$this->display();
	}	
	
	/**
	 * Category Sort
	 * @param unknown $arr
	 * @param number $parent_id
	 * @param number $lev
	 * @return multitype:number
	 */
	public function catsort1($arr,$parent_id = 0,$lev = 1){
		static $list = array();
		foreach ($arr as $v){
			if($v['pid'] == $parent_id){
				$v['lev']  = $lev;
				$list[]    = $v;
				$this->catsort1($arr,$v['id'],$lev +1);
			}
		}
		return $list;
	}
	
	/**
	 * @修改用户组的信息
	 * 
	 */
	public function mod_role(){				
		$id           =     $this->_get('id');
		$Role         =     new Model('Role');
		$role         =     $Role->where('id=' . $id)->find();
		
		//权限列表
		$Node         =     new NodeModel('node');
		$sql		  =		"
							SELECT a1 . * , a3.p_name, a2.role_id
							FROM ybr_node a1
							LEFT JOIN (							
							SELECT id, name p_name
							FROM ybr_node
							)a3 ON a3.id = a1.pid
							LEFT JOIN (							
							SELECT role_id, node_id
							FROM ybr_access
							WHERE role_id =$id
							)a2 ON a2.node_id = a1.id
							";
		$controllerList	=	$Node->query($sql);
		
		//递归排序
		$datas	=	$this->catsort1($controllerList,0,0);
		
		$list       =     array();
		foreach ($datas as $v){
			$v['blank']    =    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev'] * 2);
			$list[]        =    $v;
		}
		
		$this->assign('controllerList',$list);//权限列表	
		$this->assign('role',$role);//用户信息
		$this->display();
	}
	
	
	
	/**
	 * @节点列表
	 */
	public function node_list(){
		$Node           =    new Model('Node');
		$datas          =    $Node->select();
		$datas          =    $this->catsort($datas,0,0);
		
		$nodeList       =     array();
		foreach ($datas as $v){
			$v['name']    =    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev'] * 2).$v['name'];
			$nodeList[]        =    $v;
		}
		
		$this->assign('nodeList',$nodeList);
		$this->display();
	}
	
	/**
	 * @添加节点
	 */
	public function add_node(){
		$Node          =    new Model('Node');
		$datas         =    $Node->where('level=1 or level=2')->select();
		$datas         =    $this->catsort($datas,0,0);
		
		$nodeList       =     array();
		foreach ($datas as $v){
			$v['name']    =    str_repeat("&nbsp;&nbsp;&nbsp;",$v['lev']).$v['name'];
			$nodeList[]        =    $v;
		}		
		//t($nodeList);
		$this->assign('nodeList',$nodeList);
		$this->display();
	}
	
	/**
	 * 修改节点信息
	 * @param node_id int
	 * @param 
	 * 
	 */
	public function mod_node(){
		$NodeModel	=	M('Node');
		//NodeInfo
		$node_id	=	$this->_get('id');		
		$nodeInfo	=	$NodeModel->where("id=$node_id")->find();
		//NodeList
		$datas         =    $NodeModel->where('level=1 or level=2')->select();
		$datas         =    $this->catsort($datas,0,0);
		
		$nodeList       =     array();
		foreach ($datas as $v){
			$v['name']    =    str_repeat("&nbsp;&nbsp;&nbsp;",$v['lev']).$v['name'];
			$nodeList[]        =    $v;
		}
		//t($nodeList);
		$this->assign('nodeList',$nodeList);
		$this->assign("nodeInfo",$nodeInfo);		
		$this->display();
	}
	
	/**
	 * @给用户分配权限页面
	 *	
	 */	 
	public function allot_user_access(){
		$id                  =     	$this->_get('id');
		//用户
		$AdminUserModel      =     	new Model('AdminUser'); 
		$Role_AdminuserModel =    	new Model('RoleAdminuser'); 
		$admin               =     	$AdminUserModel->field('user_id,user_name')->where('user_id=' . $id)->find();
				
		//当前用户权限
		$role_user_info		 =		$Role_AdminuserModel->field('ybr_role.name role_name')
														->join('ybr_role on ybr_role.id=ybr_role_adminuser.role_id')
														->where('ybr_role_adminuser.user_id=' . $id)->find();
						
		//用户组列表
		$Role                =     new Model('Role');
		$roleList            =     $Role->field('id,name')->where('invalid=0')->select();
				
		$this->assign('admin',$admin);
		$this->assign('roleList',$roleList);
		$this->assign('role_user_info',$role_user_info);
		$this->display();
	}
	
	/*
	+------------------------------------------------------
	* No Ajax
	* 
	+------------------------------------------------------
	*/
	
	/**
	 * @添加用户组  
	 * @param:
	 * @param:
	 * 
	 */
	public function add_role_ok(){
		//建立一个空模型	
		$Model				=	  	new Model();
		//开启事物
		$Model->startTrans();
		$NodeModel          =    	new NodeModel('Node');
		$AccessModel        =     	new AccessModel('Access');
		$RoleModel          =     	new Model('Role');			
		
		$roleInfo['name']	=		$this->_post('name');
		$roleInfo['status']	=		$this->_post('status');
		$roleInfo['remark']	=		$this->_post('remark');
		$roleInfo['ctime']	=		time();
		$accessList			=	  	$_POST['chkGroup'];//权限列表
		//生成一个新用户组
		$role_id		 	=		$RoleModel->add($roleInfo);
		
		$accessArrayList	=		array();
		$resultArray		=		array();
		//遍历权限列表:node_id,level,pid
		foreach($accessList as $k=>$v){
			$_array							=	explode('-',$v);
			$accessArrayList['role_id']	=	$role_id;
			$accessArrayList['node_id']	=	$_array[0];
			$accessArrayList['level']	=	$_array[1];
			$accessArrayList['pid']		=	$_array[2];			
			$accessArrayList['ctime']	=	time();	
			//将该用户组权限放入权限表中
			$resultArray[$k]				=	$AccessModel->add($accessArrayList);
		}
		//是否存在false
		$result 		=	array_search(false,$resultArray) ? true : false;
		
		if ( !$result && $role_id ){
			//提交事务
			$Model->commit();
			$this->success('操作成功',U('Power/role_list'));
		}else{
		   //事务回滚		   
		   $Model->rollback();
		   $this->success('操作失败',U('Power/role_list'));
		}
	}
	
	/**
	 * @deleteAdminUser:删除管理员
	 * 
	 */
	public function delete_adminuser(){
		$id              =   $this->_post('id');
		
		$RoleUser        =   new Model('RoleAdminuser');//用户角色表
		$AdminUser       =   new Model('User');//用户表
		$userInfo		 =	 $AdminUser->where('id=' . $id)->find();
		if('admin' == $userInfo['name'])
			$this->ajaxReturn(0,'您没有权限删除该用户',1);
		
		$RoleUser->where('user_id=' . $id)->delete();
		
		$this->ajaxReturn(1,"操作成功",1);
		
//		$result          =   $AdminUser->where('id=' . $id)->delete();
//		if($result){
//			$this->ajaxReturn(1,"操作成功",1);
//		}
//		else{
//			$this->ajaxReturn(0,"操作失败",0);
//		}
	}
	
	/**
	 * @修改用户组信息
	 * 
	 */
	public function mod_role_ok(){
		$role_id             =     $this->_post('id');
		if(empty($role_id)) {
			$this->success('操作出现小问题,为您跳转到用户组列表页面',U('Power/role'));
			return;
		}
		
		//修改角色信息
		$datas          	=    array();
		$datas['name']		=	 $this->_post('name');
		$datas['status']	=	 $this->_post('status');
		$datas['remark']	=	 $this->_post('remark');		
		
		$Role           	=    new Model('Role');
		$result         	=    $Role->where('id=' . $role_id)->save($datas); 
				
		//建立一个空模型
		$Model				=	 new Model();
		//开启事物
		$Model->startTrans();
		$AccessModel        =    new AccessModel('Access');
		//先删除角色本来具有的权限
		$delete_old_access	=	 $Model->execute("delete from ybr_access where role_id=$role_id");
		//添加修改后的权限
		$accessList			=	 $_POST['chkGroup'];//权限列表		
		
		$accessArrayList	=	 array();
		$resultArray		=	 array();
		//遍历权限列表:node_id,level,pid
		foreach($accessList as $k=>$v){
			$_array						=	explode('-',$v);
			$accessArrayList['role_id']	=	$role_id;
			$accessArrayList['node_id']	=	$_array[0];
			$accessArrayList['level']	=	$_array[1];
			$accessArrayList['pid']		=	$_array[2];
			$accessArrayList['ctime']	=	time();
			//将该用户组权限放入权限表中
			$resultArray[$k]			=	$AccessModel->add($accessArrayList);
		}
		//是否存在false
		$result 		=	array_search(false,$resultArray) ? true : false;
		
		if ( ( !$result && $delete_old_access ) || $result){
			//提交事务
			$Model->commit();
			$this->success('操作成功',U('Power/role_list'));
		}else{
			//事务回滚
			$Model->rollback();
			$this->success('操作失败',U('Power/role_list'));
		}		
	}
	
	/**
	 * @删除用户组的信息
	 * 
	 */
	public function delete_role(){
		$role_id        		=     $this->_get('id');
		$Access         		=     new AccessModel('Access');
		$Role           		=     new Model('Role');
		$Role_AdminuserModel  	=     new Model('RoleAdminuser');
		
		$havePeople     		=     count($Role_AdminuserModel->where('role_id=' . $role_id)->select());
		//判断该用户组是否存在管理员
		if($havePeople != 0) {
			$this->error('该用户组有管理员,暂不能删除',U('Power/role_list'));
			return;
		}
		//删除role里面的用户组		
		$result         		=     $Role->where('id=' . $role_id)->delete();		
		//删除acess里面用户组的权限
		$Access->where('role_id=' . $role_id)->delete();
		$url            		=     U('Power/role_list');
		if($result){
			$this->success('操作成功',$url);
		}
		else{
			$this->error('操作失败',$url);
		}		
	}
	
	/**
	 * @添加节点
	 */
	public function add_node_ok(){
		$Node            =    new Model('Node');
		$Node->create();
		$id              =    $Node->add();
		$url             =    U('Power/add_node');
		
		if($id){
			$this->success('添加节点成功',$url);
		}	
		else{
			$this->success('添加节点失败',$url);
		}		
	}
	
	/**
	 * 修改节点--OK
	 * @param id int
	 * @param name string
	 * @param title string 
	 * @param status int
	 * @param remark string
	 * @param pid int
	 * @param sort int
	 * @param level int
	 * @param id
	 * 
	 */
	public function mod_node_ok(){	
		$id			=	$this->_post('id');
		$datas		=	$_POST;
		unset($datas['id']);
		
		$NodeModel	=	M('Node');
		$result		=	$NodeModel->where("id=$id")->save($datas);
		
		if($result){
			$url	=	U('Power/node_list');
			$this->success("操作成功",$url);
		}
		else{
			$url	=	U('Power/node_list');
			$this->error("操作失败",$url);
		}
	}
	
	/**
	 * @给用户分配权限
	 */
	public function allot_user_access_ok(){
		$Role_AdminuserModel         =     new Model('RoleAdminuser');
		$user_name         			 =     $this->_post('user_name');
		if($user_name == 'admin'){
			$this->error('你没有操作此用户的权限',U('Power/adminuser_list'));
			return;
		}
		unset($_POST['user_name']);
		//判断用户是否已经分配了权限
		$role_id            =     $_POST['role_id'];
		$user_id            =     $_POST['user_id'];
		$con                =     "user_id=" . $user_id;
		$isExist            =     $Role_AdminuserModel->where($con)->find();
		
		$result             =     false;
		$url                =     U('Power/adminuser_list');
		
		if($isExist){//是,则更新		
			$result         =     $Role_AdminuserModel->where("user_id=" . $user_id)->save($_POST);
		}
		else{//否,则添加
			$datas			=	  $_POST;
			$datas['ctime']	=	  time();
			$result         =     $Role_AdminuserModel->add($_POST);
		}
		
		if($result)
			$this->success('操作成功',$url);
		else
			$this->error('操作失败',$url);
	}
	
	/********** [Ajax] **********/
	public function ajaxTable(){
		$action    =    $this->_post('action');
		$id        =    $this->_post('id');
		
		switch($action){
			case 'del':
				$Role        =    new Model('Role');
				$result      =    $Role->where('id=' . $id)->delete();
				if($result){
					$this->ajaxReturn(1,'删除成功',1);
				}else{
					$this->ajaxReturn(0,'删除成功',0);
				}
			break;
		}		
	}
	
	/**
	 * @nodeAjaxTable
	 */
	public function nodeAjaxTable(){
		$action          =    $this->_post('action');
		$id              =    $this->_post('id');
		
		switch($action){
			case 'del':
				$Node        =    new Model('Node');
				$result      =    $Node->where('id=' . $id)->delete();
				if($result){
					$this->ajaxReturn(1,'删除成功',1);
				}else{
					$this->ajaxReturn(0,'删除成功',0);
				}
			break;
		}
		
	}
		  
	/**
	 * Category Sort
	 * @param unknown $arr
	 * @param number $parent_id
	 * @param number $lev
	 * @return multitype:number
	 */
	public function catsort($arr,$parent_id = 0,$lev = 1){
		static $list = array();
		foreach ($arr as $v){
			if($v['pid'] == $parent_id){
				$v['lev']  = $lev;
				$list[]    = $v;
				$this->catsort($arr,$v['id'],$lev +1);
			}
		}
		return $list;
	}
	
}